<template>
  <div class="grid-table-filter" :class="classes" @click.stop="noClick">
    <i class="grid-ico"></i>
    <div class="panel" :class="meta.timepicker || meta.timepicker === ''?'panel_timepicker':''">
      <!-- 升降序START -->
      <!-- 接口有问题，暂时屏蔽 -->
      <div class="filter-sort" v-if="meta.sort">
        <ul>
          <li class="sort-asc" :class="{ active: queryData.sort === 'asc|' + displayName + '|' + field }" @click="sortBy(field, displayName, 'ASC')">升序</li>
          <li class="sort-desc" :class="{ active: queryData.sort === 'desc|' + displayName + '|' + field }" @click="sortBy(field, displayName, 'DESC')">降序</li>
        </ul>
      </div>
      <!-- 升降序END -->
      <!-- 搜索START -->
      <div class="filter-search" v-if="meta.search || meta.search === ''">
        <img src="./images/filter-search.png">
        <span v-if="meta.searchType == 1">
          <input type="text" :maxlength=seachMaxlength v-model="search" :placeholder="searchPlaceholder" >
        </span>
        <span  v-if="meta.searchType == 2">
          <input type="text" :maxlength=seachMaxlength v-model="search" :placeholder="searchPlaceholder" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')">
        </span>
        <p class="seach_tip">*搜索词不能超过{{seachMaxlength}}个字</p>
      </div>
      <!-- 搜索END -->
      <!-- 单选框START -->
      <div class="filter-radio" v-if="meta.radio">
        <Radio-group v-model="radioChecked" v-on:on-change="radioChange" vertical>
          <Radio v-if="meta.radio.enumPairs.length > 0" v-for="(item,index) in meta.radio.enumPairs" :key="index" :preLabel="item.name" :code="item.id"></Radio>
        </Radio-group>
      </div>
      <!-- 单选框END -->
      <!-- 复选框START -->
      <div class="filter-checkbox" v-if="meta.checkbox">
        <Checkbox-group v-model="checkboxChecked" @on-change="checkboxChange">
          <Checkbox v-if="meta.checkbox.enumPairs.length > 0" v-for="(item,index) in meta.checkbox.enumPairs" :key="index" :preLabel="item.name" :code="item.id" ellipsis></Checkbox>
        </Checkbox-group>
      </div>
      <!-- 复选框END -->
      <!-- 结构树START -->
      <div class="filter-tree" v-if="meta.tree">
        <!-- 
        < src="./images/filter-search.png" />
        <input type="text" placeholder="请输入关键字" ref="treeKey" @keyup="aotoSearchTree()" /> -->
        <div class="org-content">
          <Tree :data="treeData" ref="orgTree" cancelSelect show-checkbox multiple></Tree>
        </div>
      </div>
      <!-- 结构树END -->
      <!-- 区间选择START -->
      <div class="filter-range" v-if="meta.range || meta.range === ''">
        <div class="range_warp">
          <label>从</label>
          <Input-number class="range_input" :min="0" :step="1" :maxlength="999999999999999999" v-model="rangeBegin"></Input-number><!-- :min="0" :max="rangeEnd" -->
        </div>
        <div class="range_warp">
          <label>到</label>
          <Input-number class="range_input" :step="1" :max="999999999999999999" v-model="rangeEnd"></Input-number>
        </div>
      </div>
      <!-- 区间选择END -->
      <!-- 日期选择器Star -->
      <div class="filter-timePicker" v-if="meta.timepicker || meta.timepicker === ''">
        <div class="filter-timePicker-warp" >
          <div class="timebox">
            <Date-picker
              open
              :value="timeStart"
              type="date"
              @on-change="handleChangestarttime"
              @on-ok="handleOk">
              <div class="timewarp">
                <span class="promptText">开始时间：</span>
                  <Icon type="ios-calendar-outline"></Icon>
                  <template v-if="timeStart === ''">选择日期</template>
                  <template v-else>{{ timeStart }}</template>
                  <span class="clearTime" @click="clearStartTime()"><Icon type="close-circled"></Icon></span>
              </div>
            </Date-picker>
          </div>
          <div class="timebox">
            <Date-picker
              open
              :value="timeEnd"
              type="date"
              @on-change="handleChangeendtime"
              @on-ok="handleOk">
              <div class="timewarp">
                <span class="promptText">结束时间：</span>
                  <Icon type="ios-calendar-outline"></Icon>
                  <template v-if="timeEnd === ''">选择日期</template>
                  <template v-else>{{ timeEnd }}</template>
                  <span class="clearTime" @click="clearEndTime()"><Icon type="close-circled"></Icon></span>
              </div>
            </Date-picker>
          </div>
          <div class="footerbox">
            <Button type="info" @click.stop="handleOk()">确定</Button>
            <Button @click.stop="cancel()">取消</Button>
          </div>
        </div>
      </div>
      <!-- 日期选择器End -->
      <!-- 按钮START -->
      <div class="grid-btns" v-if="meta.search || meta.search === '' || meta.checkbox || meta.tree || meta.range || meta.range === ''" >
        <Button type="primary" @click="submit">确定</Button>
        <Button @click="cancel">取消</Button>
      </div>
      <!-- 按钮END -->
    </div>
  </div>
</template>
<script>
import Rest from '@/rest'
import Helper from '@/common/helper'
//import Bus from '@/store/bus'


export default {
  data() {
      return {
        field: this.options.name, // 过滤的字段
        displayName: this.options.displayName, // 过滤的显示名称
        meta: this.options, // 过滤的初始化数据
        search: this.options.search || '', // 过滤的搜索数据
        rangeBegin: this.options.rangeBegin || null, // 过滤的搜索数据
        rangeEnd: this.options.rangeEnd || null, // 过滤的搜索数据
        searchPlaceholder: this.options.search || this.options.search === '' ? '请输入' + this.options.displayName : '', // 过滤的搜索框的placeholder
        radioChecked: '', // 单选框默认值
        checkboxChecked: [], // 复选框默认值
        checkboxcheckedObj: [], // 复选框默认值对象，格式：{"orgLevelCode":"10|区域|核算层级"}
        treeData: [], // 树结构数据
        treeOriginData: [], // 组织结构树-(备用于智能搜索)
        treeSelectedIds: [], // 选中结点
        treeSelectedNames: [],
        timeStart: this.options.timeStart || '', // 过滤的起始时间
        timeEnd: this.options.timeEnd || '', // 过滤的搜索数据
      }
    },
    methods: {
      // 确定修改时间
      handleOk () {
        var that = this;
        for (var key in that.checkboxcheckedObj) {
          if (that.checkboxcheckedObj[key] === '') {
            delete that.queryData.checked[key]
          } else {
            that.queryData.checked[key] = that.checkboxcheckedObj[key]
          }
        }
        var t1 = that.timeStart;
        var t2 = that.timeEnd;
        var canChange = false;
        if(t1 && t2){
          if(t1>t2){
            that.$Message.warning("开始时间不能大于结束时间");
          }else{
            canChange = true;
          }
        }else{
          canChange = true;
        }
        if(canChange){
          var len = that.queryData.timeList.length;
          var count = 0;
          that.queryData.timepicker = {
            name: that.field,
            displayName: that.displayName
          }
          that.queryData.timepicker[that.field+'Begin'] = t1;
          that.queryData.timepicker[that.field+'End'] = t2;
          for(var i = 0;i<len;i++){
            if(that.queryData.timeList[i].name == that.field){
              that.queryData.timeList[i][that.field+'Begin'] = t1;
              that.queryData.timeList[i][that.field+'End'] = t2;
              count++
            }
          }
          if(count == 0){
            that.queryData.timeList.push(that.queryData.timepicker);
          }
        }
        this.emitQuery()  
      },
      clearStartTime(){
        this.handleChangestarttime('')
      },
      clearEndTime(){
        this.handleChangeendtime('')
      },
      // 修改开始时间
      handleChangestarttime(date) {
        this.timeStart = date;
      },
      // 修改结束时间
      handleChangeendtime(date) {
        this.timeEnd = date;
      },
      // 阻止冒泡
      noClick() {},
      // 重置单选/复选框的默认值
      reset(name) {
        if (this.field === name) {
          this.radioChecked = ''
          this.checkboxChecked = []
          this.checkboxcheckedObj = []
          if (name === 'caseBelong') {
            this.initTreeList()
          }
        }
      },
      // 点击排序触发的函数
      sortBy(field, displayName, sortType) {
        this.queryData.sort = sortType + '|' + displayName + '|' + field
        this.emitQuery()
      },
      // 点击单选触发的函数
      radioChange() {
        var radioCheckedId = this.radioChecked
        var radioCheckedName = ''
        this.meta.radio.enumPairs.forEach(function(item) {
          if (item.id == radioCheckedId) radioCheckedName = item.name
        })
        this.queryData.checked[this.field] = this.radioChecked + '|' + radioCheckedName + '|' + this.displayName
        this.emitQuery()
      },
      // 点击复选触发的函数
      checkboxChange() {
        var checkboxCheckedIds = this.checkboxChecked
        var checkboxCheckedNames = []
        var _this = this
        checkboxCheckedIds.forEach(function(id) {
          _this.meta.checkbox.enumPairs.forEach(function(item) {
            if (item.id == id) checkboxCheckedNames.push(item.name)
          })
        })

        if (this.checkboxChecked.length > 0) {
          this.checkboxcheckedObj[this.field] = this.checkboxChecked.join(',') + '|' + checkboxCheckedNames.join(',') + '|' + this.displayName;
        } else {
          this.checkboxcheckedObj[this.field] = '';
        }
      },
      // 点击确定
      submit() {
        var that = this;
        // 获取树选中结点
        function getOrgIds(data) {
          data.forEach(function(i) {
            that.treeSelectedIds.push(i.orgId)
            that.treeSelectedNames.push(i.title)
            if (i.children) {
              getOrgIds(i.children)
            }
          })
        }
        for (var key in that.checkboxcheckedObj) {
          if (that.checkboxcheckedObj[key] === '') {
            delete that.queryData.checked[key]
          } else {
            that.queryData.checked[key] = that.checkboxcheckedObj[key]
          }
        }
        // todo search应该改为数组，以支持多个名称类型搜索
        if (that.search) {
          var len = that.queryData.searchList.length;
          var count = 0;
          that.queryData.search={
            value: that.search.replace(/(^\s*)|(\s*$)/g, ""),
            name: that.field,
            displayName: that.displayName
          }
          for(var i = 0;i<len;i++){
            if(that.queryData.searchList[i].name == that.field){
              that.queryData.searchList[i].value = that.search.replace(/(^\s*)|(\s*$)/g, "");
              count++
            }
          }
          if(count == 0){
            that.queryData.searchList.push(that.queryData.search);
          }
        }
        // 区间选择
        // (that.rangeBegin || that.rangeBegin == 0)  && (that.rangeEnd || that.rangeEnd == 0) && that.rangeEnd >=0
        if ((that.rangeBegin || that.rangeBegin == 0) || (that.rangeEnd || that.rangeEnd == 0)) {  
          var r1 = that.rangeBegin;
          var r2 = that.rangeEnd;
          var canChange = false;
          var len = that.queryData.rangeList.length;
          var count = 0;
          console.log(r1)
          console.log(r2)
          if((r1 || r1==0) && (r2 || r2==0)){
            if(r1>r2){
              that.$Message.warning("起始值不能大于结束值");
            }else{
              canChange = true;
            }
          }else{
            canChange = true;
          }
          if(canChange){
            that.queryData.range = {
              name: that.field,
              displayName: that.displayName
            }
            if(that.rangeBegin || that.rangeBegin==0){
              that.queryData.range[that.field+'Begin'] = that.rangeBegin;
            }
            if(that.rangeEnd || that.rangeEnd==0){
              that.queryData.range[that.field+'End'] = that.rangeEnd;
            }
            for(var i = 0;i<len;i++){
              if(that.queryData.rangeList[i].name == that.field){
                if(that.rangeBegin || that.rangeBegin==0){
                  that.queryData.rangeList[i][that.field+'Begin'] = that.rangeBegin;
                }
                if(that.rangeEnd || that.rangeEnd==0){
                  that.queryData.rangeList[i][that.field+'End'] = that.rangeEnd;
                }
                count++
              }
            }
            if(count == 0){
              console.log(that.queryData)
              that.queryData.rangeList.push(that.queryData.range);
            }
          }
        }
        if (that.field === 'caseBelong') {
          that.treeSelectedIds = [];
          that.treeSelectedNames = [];
          getOrgIds(that.$refs.orgTree.getCheckedNodes());
          if (that.treeSelectedIds.length > 0) {
            that.queryData.tree.value = that.treeSelectedIds.join();
            that.queryData.tree.name = that.treeSelectedNames.join();
          } else {
            that.queryData.tree.value = '';
            that.queryData.tree.name = '';
          }
        }
        this.emitQuery()  
      },
      // 点击取消
      cancel() {
        this.$emit('filter', null)
      },
      emitQuery() {
        this.$emit('filter', this.queryData);
      },
      // 处理函数 - 处理树结构数据
      getChildTree(item) {
        var that = this;
        var cloneObj = function(arr) {
          var arr2 = [];
          for (var i = 0, len = arr.length; i < len; i++) {
            var arr3 = {};
            arr3.title = arr[i].orgName;
            arr3.orgId = arr[i].orgId;
            if (arr[i].childList != null) {
              arr3.children = cloneObj(arr[i].childList);
            } else {
              arr3.children = null;
            }

            arr2.push(arr3);
          }
          return arr2;
        }
        that.treeData = cloneObj(item);
      },
      // 初始化树数据
      initTreeList() {
        var that = this
        var treeDataNew = Helper.get('treeData') ? JSON.parse(Helper.get('treeData')) : ''
        that.treeData = []
        this.getChildTree(treeDataNew)
      },
      // 智能搜索组织结构
      aotoSearchTree() {
        var that = this
          // console.log(that.$refs.treeKey.value);
          // todo 搜索树 暂不处理
      }
    },
    mounted() {
      var _this = this;
      // 日期选择
      if (_this.meta.timepicker || _this.meta.timepicker === '') {
        _this.queryData.timepicker = {
          value: '',
          name: _this.meta.name,
          displayName: _this.meta.displayName
        }
        _this.queryData.timeList = [];
        _this.queryData.timepicker[_this.meta.name+'Begin'] = '';
        _this.queryData.timepicker[_this.meta.name+'End'] = '';
      }
      // 文本
      if (this.meta.search || this.meta.search === '') {
        this.queryData.search = {
          value: '',
          name: this.meta.name,
          displayName: this.meta.displayName
        }
      }
      // 区间
      if (this.meta.range || this.meta.range === '') {
        this.queryData.range = {
          name: this.meta.name,
          displayName: this.meta.displayName
        }
        this.queryData.range[this.meta.name+'Begin'] = null;
        this.queryData.range[this.meta.name+'End'] = null;
      }
      // 复选
      if (this.meta.checkbox) {
        var retrieveUrl = this.meta.checkbox.retrieveUrl
        if (retrieveUrl) {
          Rest.get(retrieveUrl,this.meta.parms).done(function(res) {
            if (Helper.isSuccess(res)) {
              _this.meta.checkbox.enumPairs = res.data
            } else {
              _this.$message.warning(res.status.msg)
            }
          })
        }
      }
      // 单选
      if (this.meta.radio) {
        var retrieveUrl = this.meta.radio.retrieveUrl
        if (retrieveUrl) {
          Rest.get(retrieveUrl,this.meta.parms).done(function(res) {
            if (Helper.isSuccess(res)) {
              _this.meta.radio.enumPairs = res.data
            } else {
              _this.$message.warning(res.status.msg)
            }
          })
        }
      }
      // 组织机构树
      if (this.meta.tree) {
        this.queryData.tree.displayName = this.meta.displayName
        this.initTreeList()
      }
    },
    created() {
      var that = this;
      // 解决时间选择器错位的问题
      setTimeout(()=>{
        $(".filter-timePicker").find(".ivu-select-dropdown").each((index,item)=>{
          item.style.top = '';
          item.style.left = '';
        })
      },50)
      
      Bus.$on("removeFilter_search", function(name) {
        if (name) {
          var len = that.queryData.searchList.length;
          var index = Helper.getIndex(that.queryData.searchList,'name',name);
          if(index>-1){
            that.queryData.searchList.splice(index,1)
          }
        }
        that.search = ''; // 清空过滤的搜索数据
      });
      Bus.$on("removeFilter_range", function(name) {
        if (name) {
          var len = that.queryData.rangeList.length;
          var index = Helper.getIndex(that.queryData.rangeList,'name',name);
          if(index>-1){
            that.queryData.rangeList.splice(index,1)
          }
        }
        that.rangeBegin = null; // 清空过滤的搜索数据
        that.rangeEnd = null;
      });
      Bus.$on("removeFilter_timepicker", function(name) {
        if (name) {
          if(that.queryData.timeList){
            var len = that.queryData.timeList.length;
            var index = Helper.getIndex(that.queryData.timeList,'name',name);
            if(index>-1){
              that.queryData.timeList.splice(index,1)
            } 
          }else{
            that.queryData.timeList = [];
          }
        }
        that.timeStart = ''; // 清空过滤的搜索数据
        that.timeEnd = '';
      });
    },
    props: {
      options: {
        type: Object,
        default: {}
      },
      classes: {
        type: Array,
        default: []
      },
      seachMaxlength: {
        type: Number,
      },
      queryData: {
        type: Object,
        default: function() {
          return {
            sort: '',
            search: {
              value: '',
              displayName: ''
            },
            checked: {},
            tree: {
              key: 'orgIds',
              value: '',
              name: '',
              displayName: ''
            },
            range: {
              name: '',
              displayName: '',
              rangeBegin: 0,
              rangeEnd: 0
            },
            searchList:[],
            rangeList:[],
            timepicker: {
              name: '',
              displayName: '',
              timeStart: 0,
              timeEnd: 0
            },
            timeList:[],
          }
        }
      }
    },
}
</script>
<style lang="scss" scoped>
@import "../../assets/sass/install";
.grid-table-filter {
  position: relative;
  z-index: 3;
  display: inline-block;
  vertical-align: middle;
  color: #697077;
  .grid-ico {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 2px;
    width: 21px;
    height: 21px;
    cursor: pointer;
    background-image: url(./images/filter-default.png);
    background-repeat: no-repeat;
    background-position: 0 0;
  }
  .panel {
    width: auto;
    min-width: 218px;
    background-color: white;
    @include radius(5px);
    box-shadow: 0px 0px 20px 2px rgba(0, 0, 0, .2);
    text-align: center;
    position: absolute;
    left: -99px;
    top: 28px;
    line-height: normal;
    display: none;
    cursor: default;
    padding-top: 10px;
    &:before {
      content: '';
      display: block;
      width: 0;
      height: 0;
      border: 10px solid transparent;
      border-bottom-color: white;
      position: absolute;
      top: -16px;
      left: 99px;
    }
    &.panel_timepicker{
      left: -250px;
      &:before {
        left: 250px;
      }
    }
    .filter-timePicker{
      text-align: left;
      width: 515px;
      .filter-timePicker-warp{
        cursor: default;
        width: 100%;
        overflow: auto;
        box-sizing: border-box;
        z-index: 900;
        .timebox{
          position: relative;
          display: inline-block;
          width: 240px;
          height: 294px;  
          background-color: #f5f5f5;
          padding: 8px;
          margin-left: 10px;
          @include radius(3px);
        }
        .timewarp{
          height: 30px;
          color: #02b0f0;
          &:hover{
            .clearTime{
              display: inline-block;
            }
          }
        }
        .promptText{
          color: #666;
        }
        .footerbox{
          margin-top: 5px;
          width: 100%;
          text-align: right;
          padding:5px 15px;
          border-top: 1px solid #ddd;
        }
        .clearTime{
          display: none;
          float: right;
          font-size: 16px;
          height: 25px;
          margin-right: 8px;
          margin-top: -1px;
          color: #999;
          cursor: pointer;
        }
      }
    }
    .filter-tree {
      display: inline-block;
      width: 218px;
      height: 34px;
      padding-bottom: 15px;
      text-align: left;
    }
    .filter-search {
      cursor: default;
      width: 218px;
      height: 100px;
      padding: 15px;
      padding-top: 0;
      padding-bottom: 15px;
      text-align: left;
      position: relative;
      input {
        @include radius(32px);
        height: 32px;
        line-height: 33px;
        width: 100%;
        border: none;
        background-color: #e9eded;
        padding-left: 35px;
        padding-right: 20px;
      }
      img {
        position: absolute;
        top: 9px;
        left: 25px;
        cursor: default;
      }
      .seach_tip {
        font-size: 12px;
        color: #999;
        padding: 10px 5px 0 2px;
      } 
    }
    .filter-sort {
      padding-bottom: 10px;
      ul {
        text-align: left;
        li {
          padding: 3px 20px;
          text-align: left;
          cursor: pointer;
          display: inline-block;
          vertical-align: top;
          /*flex-direction: row;*/
          /*align-items: center;*/
          &.active {
            color: $blue;
            &:before {
              background-position: -17px 0;
            }
          }
          &:before {
            content: '';
            width: 17px;
            height: 14px;
            display: inline-block;
            vertical-align: middle;
            background-repeat: no-repeat;
            margin-right: 5px;
          }
          &.sort-asc {
            &:before {
              background-image: url(./images/sort-asc.png);
              background-position: 0 0;
            }
          }
          &.sort-desc {
            &:before {
              background-image: url(./images/sort-desc.png);
              background-position: 0 0;
            }
          }
          &:hover {
            color: $blue;
            &:before {
              background-position: -17px 0;
            }
          }
        }
      }
    }
    .filter-range{
      background: #f5f5f5;
      width: 182px;
      margin: 0 auto; 
      margin-bottom: 15px;
      padding: 15px;
      text-align: left;
      color: #111;
      font-size: 14px;
      .range_input{
        width: 100%;
        margin-top: 5px;
      }
      .range_warp{
        margin-bottom: 15px;
      }
    }
    .filter-checkbox{
      margin-bottom: 15px;
    }
    .filter-radio{
      /*margin-bottom: 15px;*/
    }
    .filter-checkbox,.filter-radio{
      text-align: left;
      max-height: 242px;
      overflow: auto;
      @include overflowCss(); 
    }  
  }
  &.active {
    .grid-ico {
      background-image: url(./images/filter-active.png);
    }
    .panel {
      display: block;
    }
  }
}

.ivu-checkbox-group {
  display: block;
  .ivu-checkbox-group-item {
    display: block;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 5px 20px;
    margin-right: 0;
    &:hover {
      background-color: #f1f5f5;
      color: $blue;
    }
  }
}

.ivu-radio-group {
  display: block;
  padding-bottom: 15px;
  .ivu-radio-group-item {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 5px 20px;
    margin-right: 0;
    &:hover {
      background-color: #f1f5f5;
      color: $blue;
    }
  }
}

.grid-btns {
  border-top: 1px solid $borderColor;
  padding-top: 10px;
  padding-bottom: 10px;
  button {
    &:first-child {
      margin-right: 5px;
    }
  }
}

.org-content {
  width: 218px;
  height: 150px;
  background: #fdfdfd;
  margin-top: 5px;
  overflow-y: auto;
  overflow-x: hidden;
}

.ivu-tree-arrow-hidden {
  cursor: auto;
  width: 14px;
  display: inline-block;
  height: 16px;
}


</style>
